package quq.missq.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;

import java.util.ArrayList;

import quq.missq.BaseActivity;
import quq.missq.MLog;
import quq.missq.R;
import quq.missq.huanxin.ImageUtils;
import quq.missq.utils.ImageLoadInterface;
import quq.missq.utils.ImageLoadUtil;
import quq.missq.utils.ImageUtil;
import quq.missq.utils.PhotoUtil;
import quq.missq.views.ImageViewPager;
import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher;


public class ImageViewPagerActivity extends BaseActivity implements ImageLoader.ImageListener {

    public static ImageViewPagerActivity instance = null;

    private ImageViewPager viewPager;
    private TextView textView1;
    private TextView textView2;

    private int position;
    private ArrayList<String> imageUrlList;

    /**
     * 在这里添加了启动动画
     */
    public static void launcher(Context context, ArrayList<String> imageUrlList, int position) {
        /*Intent intent = new Intent(context, CommonViewPagerActivity.class);
		intent.putExtra("netImageUrls", imageUrlList);
		intent.putExtra("position", position);
		context.startActivity(intent);
		((Activity)context).overridePendingTransition(R.anim.activity_imageviewpager_in, R.anim.activity_nothing);*/
    }

    /**
     * 退出动画
     */
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_UP && event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            finish();
            overridePendingTransition(R.anim.activity_nothing, R.anim.activity_imageviewpager_out);
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.image_view_viewpager_activity);

        instance = this;
        if (getIntent().hasExtra("netImageUrls")) {
            position = getIntent().getIntExtra("position", 0);
            imageUrlList = getIntent().getStringArrayListExtra("netImageUrls");
            MLog.e(imageUrlList.get(0));
        }

        // 自定义ViewPager
        viewPager = (ImageViewPager) findViewById(R.id.myImageViewPager);
        viewPager.setOffscreenPageLimit(3);
        viewPager.setAdapter(new SamplePagerAdapter());
        viewPager.setCurrentItem(position, false);

        // 当前下标/总数(例子：2/10)
        textView1 = (TextView) findViewById(R.id.textView1);
        textView2 = (TextView) findViewById(R.id.textView2);
        textView2.setText(imageUrlList.size() + "");
        if (imageUrlList.size() <= 1) {
            findViewById(R.id.linearLayout).setVisibility(View.GONE);
        }
    }

    @Override
    public void onResponse(ImageLoader.ImageContainer imageContainer, boolean b) {

    }

    @Override
    public void onErrorResponse(VolleyError volleyError) {

    }

    /**
     * 图片适配器
     */
    class SamplePagerAdapter extends PagerAdapter {

        @Override
        public void startUpdate(ViewGroup container) {
            super.startUpdate(container);
            // 切换时修改下标
            textView1.setText((viewPager.getCurrentItem() + 1) + "");
        }

        @Override
        public int getCount() {
            return imageUrlList.size();
        }

        @Override
        public View instantiateItem(ViewGroup container, int position) {
            // 第三方PhotoView,嵌套在ViewPager中,支持缩放什么的
            final PhotoView photoView = new PhotoView(container.getContext());
            photoView.setMaxScale(10);

            // 图片地址
            String bigImageUrl = imageUrlList.get(position);
            photoView.setTag(bigImageUrl);

            // TODO 图片来源[ Res, SDCard, Net; (Assest不作考虑)]
            // 先从本地取数据，取不到就拿网络的，不判断
//			if(bigImageUrl.contains("http")){
//            VolleyTool.getImageLoader().get( bigImageUrl, new ImageLoader.ImageListener() {
//				@Override
//				public void onResponse(ImageLoader.ImageContainer imageContainer, boolean b) {
//					if (imageContainer != null && imageContainer.getBitmap() != null) {
//						photoView.setImageBitmap(imageContainer.getBitmap());
//					} else {
//						photoView.setImageResource(R.mipmap.empty_photo);
//					}
//
//				}
//
//				@Override
//				public void onErrorResponse(VolleyError volleyError) {
//					photoView.setImageResource(R.mipmap.empty_photo);
//				}
//			});}
//            else {
//				Bitmap bmp = ImageUtil.readFile(bigImageUrl);
//				photoView.setImageBitmap(bmp);
//			}
            Bitmap bitmap = null;
            bitmap = ImageUtil.readFile(bigImageUrl);
            if (bitmap != null) {
                photoView.setImageBitmap(bitmap);
            } else {
                ImageLoadUtil.loadImage(photoView, bigImageUrl, R.mipmap.empty_photo);
            }

            // 轻敲退出
            photoView.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {
                @Override
                public void onPhotoTap(View arg0, float arg1, float arg2) {
                    if (instance != null) {
                        finish();
                        overridePendingTransition(R.anim.activity_nothing, R.anim.activity_imageviewpager_out);
                    }
                }
            });

            // 长按保存     干掉长安保存
            final Bitmap finalBitmap = bitmap;
            photoView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(ImageViewPagerActivity.this);
                    final CharSequence[] items = {"保存图片"};

                    builder.setTitle("选择操作");
                    builder.setItems(items, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int item) {
                            if (items[item].equals("保存图片")) {
                                // ImageUtil.saveImage(ImageViewPagerActivity.this,(String)photoView.getTag());
                                boolean b = ImageUtil.saveImageToGallery(ImageViewPagerActivity.this, ((BitmapDrawable) photoView.getDrawable()).getBitmap());
                                if (b) {
                                    showToast("图片保存成功");
                                } else {
                                    showToast("图片保存失败");
                                }


                            }
                        }
                    });
                    builder.show();
                    return false;
                }
            });
            container.addView(photoView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            return photoView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

    }


    /**
     * 当设备配置信息有改动（比如屏幕方向的改变，实体键盘的推开或合上等）时， 并且如果此时有activity正在运行，系统会调用这个函数。 注意：
     * onConfigurationChanged只会监测应用程序在AnroidMainifest.xml中通过
     * android:configChanges="xxxx"指定的配置类型的改动；
     * 而对于其他配置的更改，则系统会onDestroy()当前Activity，然后重启一个新的Activity实例。
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // 检测屏幕的方向：纵向或横向
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            // 当前为横屏， 在此处添加额外的处理代码
        } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            // 当前为竖屏， 在此处添加额外的处理代码
        }

        // 检测实体键盘的状态：推出或者合上
        if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) {
            // 实体键盘处于推出状态，在此处添加额外的处理代码
        } else if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES) {
            // 实体键盘处于合上状态，在此处添加额外的处理代码
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }

}